package com.yxh.fragment;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ScrollView;
import android.widget.TextView;

import com.yxh.R;
import com.yxh.ZybApplication;
import com.yxh.activity.ClassTimeSettingActivity;
import com.yxh.activity.MainActivity;
import com.yxh.adapter.ClassAdapter;
import com.yxh.dto.LessonDto;
import com.yxh.service.Task;
import com.yxh.util.AppUtils;
import com.yxh.util.LogUtil;
import com.yxh.view.CommonDialog;
import com.yxh.view.LoadingLayout;
import com.yxh.view.pulltorefresh.PullToRefreshBase;
import com.yxh.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.yxh.view.pulltorefresh.PullToRefreshScrollView;
import com.yxh.view.swipemenulistview.SwipeMenu;
import com.yxh.view.swipemenulistview.SwipeMenuCreator;
import com.yxh.view.swipemenulistview.SwipeMenuItem;
import com.yxh.view.swipemenulistview.SwipeMenuListView;

/**
 * 我的课程 Fragemnt
 * 
 */
public class ClassFragment extends BaseFragment {

	public final static int CLASS_REQUEST_TIME = 0;

	private LoadingLayout loadingLayout;
	private SwipeMenuListView mListView;
	private List<LessonDto> cList;
	private ClassAdapter mAdapter;
	private Context mContext;
	private MainActivity act;
	private int[] noScrowArray;
	private PullToRefreshScrollView mPullRefreshScrollView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = ZybApplication.getContext();
		act = (MainActivity) getActivity();
		cList = new ArrayList<LessonDto>();
		noScrowArray = new int[] { -1, -1, -1 };
	}

	@SuppressLint("InflateParams")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_class, null);

		initViews(view);

		initData();

		initRegisterReceiver();

		return view;

	}

	private void initViews(View view) {

		/** loading view **/
		loadingLayout = (LoadingLayout) view.findViewById(R.id.loading_layout);
		loadingLayout.showLoading();
		loadingLayout.setOnRetryClickListener((new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				initData();
			}
		}));

		/*** top view ***/
		((TextView) view.findViewById(R.id.head_layout_tv)).setText("我的课程");
		view.findViewById(R.id.head_layout_back).setVisibility(View.GONE);

		mListView = (SwipeMenuListView) view.findViewById(R.id.listView);
		mAdapter = new ClassAdapter(getActivity(), cList);

		mListView.setNoScorwArray(noScrowArray);
		mListView.setAdapter(mAdapter);
		// setListViewHeightBasedOnChildren(mListView);
		// step 1. create a MenuCreator
		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// create "delete" item
				SwipeMenuItem deleteItem = new SwipeMenuItem(mContext);
				// set item background
				deleteItem
						.setBackground(R.drawable.main_home_bottom_list_right_bg);
				// set item width
				deleteItem.setWidth(AppUtils.dp2px(mContext, 75));
				// set a icon
				deleteItem.setIcon(R.drawable.class_listview_delete);
				// add to menu
				menu.addMenuItem(deleteItem);
			}
		};

		// set creator
		mListView.setMenuCreator(creator);
		// step 2. listener item click event
		mListView
				.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
					@Override
					public boolean onMenuItemClick(int pos, SwipeMenu menu,
							int index) {
						switch (index) {
						case 0:
							goCancleLesson(cList.get(pos).lessonId);

							break;
						default:
							break;
						}
						return false;
					}
				});

		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				Intent it = new Intent(getActivity(),
						ClassTimeSettingActivity.class);
				LessonDto lDto = cList.get(pos);
				if ("0".equals(lDto.state)) {// 0:当前
					it.putExtra("resource", "2");
					it.putExtra("dto", lDto);
					startActivity(it);
				} else if ("1".equals(lDto.state)) {// 1:已完成
					showReAddClassDialog(lDto.lessonId);
				} else if ("2".equals(lDto.state)) {// 2: 已取消
					showReAddClassDialog(lDto.lessonId);
				}

			}

		});

		mPullRefreshScrollView = (PullToRefreshScrollView) view
				.findViewById(R.id.pull_refresh_scrollview);
		mPullRefreshScrollView
				.setOnRefreshListener(new OnRefreshListener<ScrollView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ScrollView> refreshView) {
						getMyClassData(0);
					}
				});

	}

	private void initData() {
		loadingLayout.showLoading();
		getMyClassData(0);
	}

	public void getMyClassData(int isShowDialog) {
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("s", "lesson/mine");
		act.getData(map, Task.GET_MY_LESSON_FRAGMENT, isShowDialog);
	}

	private void goCancleLesson(String lesson_id) {
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("s", "lesson/cancel");
		map.put("lesson_id", lesson_id);
		act.getData(map, Task.CANCEL_LESSON_FRAGMENT, 1);

	}

	private void showReAddClassDialog(final String lessonId) {

		AppUtils.showNoTitleDialog(act, "您是否要重新添加该课程?", new OnClickListener() {
			@Override
			public void onClick(View v) {
				CommonDialog dialog = (CommonDialog) v.getTag();
				dialog.dismiss();
				goAddClass(lessonId);
			}
		}, new OnClickListener() {
			@Override
			public void onClick(View v) {
				CommonDialog dialog = (CommonDialog) v.getTag();
				dialog.dismiss();
			}

		});

	}

	private void goAddClass(String lessonId) {

		if (TextUtils.isEmpty(lessonId)) {
			LogUtil.e("课程添加参数异常");
			return;
		}

		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("s", "lesson/add_lesson");
		map.put("lesson_ids", lessonId);
		act.getData(map, Task.ADD_LESSON_CLASS_FRAGMENT, 1);

	}

	/**
	 * 刷新当前数据
	 */
	public void refurshData(List<LessonDto> li) {
		long t1 = System.currentTimeMillis();
		
		cList.clear();
		cList.addAll(li);
		noScrowArray[0] = -1;
		noScrowArray[1] = -1;
		noScrowArray[2] = -1;
		for (int i = 0; i < cList.size(); i++) {
			if (cList.get(i).state.equals("0") && noScrowArray[0] == -1) {
				noScrowArray[0] = i;
				cList.add(noScrowArray[0],
						new LessonDto("-1", String.valueOf(0), "0"));
			} else if (cList.get(i).state.equals("1") && noScrowArray[1] == -1) {
				noScrowArray[1] = i;
				cList.add(noScrowArray[1],
						new LessonDto("-1", String.valueOf(1), "0"));
			} else if (cList.get(i).state.equals("2") && noScrowArray[2] == -1) {
				noScrowArray[2] = i;
				cList.add(noScrowArray[2],
						new LessonDto("-1", String.valueOf(2), "0"));
			} else {
				cList.get(i).isTitle = "1";
			}
		}
		mListView.setNoScorwArray(noScrowArray);
		mAdapter.notifyDataSetChanged();

		if (mPullRefreshScrollView != null)
			mPullRefreshScrollView.onRefreshComplete();
		
		if (loadingLayout != null) {
			loadingLayout.showContent();
		}
		
		long t2 = System.currentTimeMillis();
		LogUtil.e("t2-t1 -->" + (t2 - t1));
		// mListView.setAdapter(mAdapter);
		// setListViewHeightBasedOnChildren(mListView);
	}

	public void loadingLayoutShowEmpty() {
		loadingLayout.showEmpty();
	}

	public void loadingLayoutShowError() {
		loadingLayout.showError();
	}

	/**
	 * 注册广播
	 */
	public static final String COM_REFRUSH_CLASS = "refresh.classfragment.for.settingtime";
	private BroadcastReceiver classReceiver;

	private void initRegisterReceiver() {
		classReceiver = new BroadcastReceiver() {
			public void onReceive(Context context, Intent i) {
				String action = i.getAction();
				if (action.equals(COM_REFRUSH_CLASS)) {
					getMyClassData(1);// 刷新Fragment
				}
			}
		};

		IntentFilter i = new IntentFilter();
		i.addAction(COM_REFRUSH_CLASS);
		getActivity().registerReceiver(classReceiver, i);
	}

	private void unregisterReceiver() {
		getActivity().unregisterReceiver(classReceiver);
	}

	@Override
	public void onDestroy() {
		unregisterReceiver();
		super.onDestroy();
	}

	/**** xxx ***/

	public void addClassItem() {
		getMyClassData(0);
		act.sendBroadcast(new Intent(HomeFragment.REFRUSH_HOME_ADD_CLASS));
	}

	public void removeClassItem(String classId) {
		// LogUtil.e("classId -->" + classId);
		// initData();
		getMyClassData(0);
		act.sendBroadcast(new Intent(HomeFragment.REFRUSH_HOME_DEL_CLASS));
	}

	/**
	 * 动态设置ListView的高度
	 * 
	 * @param listView
	 */
	public static void setListViewHeightBasedOnChildren(
			SwipeMenuListView listView) {
		if (listView == null)
			return;

		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}

		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}
}
